import os
import time 
import re
import json
import configparser
import setting as c
from core.log import logger

def log_title(title):
    logger.info("")
    logger.info(f'--------   {title}    ----------')
    # logger.info()
    
# This is for timing
def timer_elapse(func):
    def func_wrapper(*args,**kwargs):
        from time import time
        time_start = time()
        result = func(*args,**kwargs)
        time_end = time()
        time_spend = time_end - time_start
        logger.info(f'--------   {func.__name__} cost time {time_spend} s --------')
        return result
    return func_wrapper

def delete_file(file_path):
    try:
        os.remove(file_path)
        logger.info(f"文件 {file_path} 删除成功")
    except OSError as e:
        logger.info(f"删除文件 {file_path} 失败: {e}")

def time_str():
    localtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    #系统当前时间年份
    year=time.strftime('%Y',time.localtime(time.time()))
    #月份
    month=time.strftime('%m',time.localtime(time.time()))
    #日期
    day=time.strftime('%d',time.localtime(time.time()))
    #具体时间 小时分钟毫秒
    mdhms=time.strftime('%m%d%H%M%S',time.localtime(time.time()))
    return f'{year}_{month}_{day}_{mdhms}'

def dir_create(path):
    if not os.path.exists(path):
        os.makedirs(path)
        logger.info(f'文件夹创建 -> {path}')
        
def dir_check():
    log_title('文件夹检查')
    dir_List = [
        c.appdata_path,
        c.img_dir_path,
        c.shot_dir_path, 
        c.flag_dir_path,
        c.flag_wp_dir_path,
        c.log_path,
        c.config_dir_path,
        c.flag_tag_dir_path,
        c.flag_match_dir_path,
        c.flag_miss_dir_path,
        ]
    for path in dir_List:
        dir_create(path)
        
        logger.info(f'\t{path}\t\tok')
    return True

def dumpini_user(username, email, token, invitation):
    try:
        logger.info(f"start dump user {username} {email} {token} {invitation}")
        # 创建ConfigParser对象
        config = configparser.ConfigParser()

        # 添加一个新的section
        section = c.INI_USER_SECTION
        config.add_section(section)
        
        option = c.INI_USER_OPTION_USERNAME
        value = username
        config.set(section, option, value)
        
        option = c.INI_USER_OPTION_EMAIL
        value = email
        config.set(section, option, value)
        
        option = c.INI_USER_OPTION_TOKEN
        value = token
        config.set(section, option, value)
        
        option = c.INI_USER_OPTION_INVITATION
        value = invitation
        config.set(section, option, value)

        # 写入到文件
        with open(c.appdata_user_ini, 'w') as configfile:
            config.write(configfile)
            logger.info(f"dump user {username} {email} {invitation}")
    except FileNotFoundError:
        logger.error(f"File not found error. Unable to open file: {c.appdata_user_ini}")
    except PermissionError:
        logger.error(f"Permission error. Unable to write to file: {c.appdata_user_ini}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {str(e)}")
        

def loadini_user():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.appdata_user_ini)
    logger.info(c.appdata_user_ini)
    
    if ok == False:
        return None, ok

    # 访问其中的值
    section = c.INI_USER_SECTION
    username = ""
    email = ""
    token = ""
    invitation = ""
    try:
        username = config.get(section, c.INI_USER_OPTION_USERNAME)
        email = config.get(section, c.INI_USER_OPTION_EMAIL)
        token = config.get(section, c.INI_USER_OPTION_TOKEN)
        invitation = config.get(section, c.INI_USER_OPTION_INVITATION)
    except configparser.NoSectionError:
        logger.info(f"{section} OPTION not exised!")
        return None, False
    logger.info(username, email, token, invitation)
    return (username, email, token, invitation), True

def is_valid_email(email):
    pattern = r'^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None 

def clearini_user():
    delete_file(c.appdata_user_ini)
    
    
def dumpini_setting(ip, port, version):
    try:
        logger.info(f"start dump setting {ip} {port} {version}")
        # 创建ConfigParser对象
        config = configparser.ConfigParser()

        # 添加一个新的section
        section = c.INI_SETTING_SECTION
        config.add_section(section)
        
        option = c.INI_SETTING_OPTION_IP
        value = ip
        config.set(section, option, value)
        
        option = c.INI_SETTING_OPTION_PORT
        value = port
        config.set(section, option, value)
        
        option = c.INI_SETTING_OPTION_VERSION
        value = version
        config.set(section, option, value)

        # 写入到文件
        with open(c.appdata_setting_ini, 'w') as configfile:
            config.write(configfile)
            logger.info(f"dump setting {ip} {port} {version}")
    except FileNotFoundError:
        logger.error(f"File not found error. Unable to open file: {c.appdata_setting_ini}")
    except PermissionError:
        logger.error(f"Permission error. Unable to write to file: {c.appdata_setting_ini}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {str(e)}")
        

def loadini_setting():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.appdata_setting_ini)
    logger.info(c.appdata_setting_ini)
    
    if ok == False:
        return None, ok

    # 访问其中的值
    section = c.INI_SETTING_SECTION
    ip = ""
    port = ""
    try:
        ip = config.get(section, c.INI_SETTING_OPTION_IP)
        port = config.get(section, c.INI_SETTING_OPTION_PORT)
        version = config.get(section, c.INI_SETTING_OPTION_VERSION)
    except configparser.NoSectionError:
        logger.info(f"{section} OPTION not existed!")
        return None, False
    res = (ip, port, version)
    logger.info(res)
    return res, True

def clearini_setting():
    delete_file(c.appdata_setting_ini)
    
    
def dumpini_annc(server, sponsor):
    try:
        logger.info(f"start dump annc {server} {sponsor}")
        # 创建ConfigParser对象
        config = configparser.ConfigParser()

        # 添加一个新的section
        section = c.INI_ANNC_SECTION
        config.add_section(section)
        
        option = c.INI_ANNC_OPTION_SERVER
        value = server
        config.set(section, option, value)
        
        option = c.INI_ANNC_OPTION_SPONSOR
        value = sponsor
        config.set(section, option, value)

        # 写入到文件
        with open(c.appdata_annc_ini, 'w') as configfile:
            config.write(configfile)
            logger.info(f"dump annc {server} {sponsor}")
    except FileNotFoundError:
        logger.error(f"File not found error. Unable to open file: {c.appdata_annc_ini}")
    except PermissionError:
        logger.error(f"Permission error. Unable to write to file: {c.appdata_annc_ini}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {str(e)}")
        

def loadini_annc():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.appdata_annc_ini)
    logger.info(c.appdata_annc_ini)
    
    if ok == False:
        return None, ok

    # 访问其中的值
    section = c.INI_ANNC_SECTION
    server = ""
    sponsor = ""
    try:
        server = config.get(section, c.INI_ANNC_OPTION_SERVER)
        sponsor = config.get(section, c.INI_ANNC_OPTION_SPONSOR)
    except configparser.NoSectionError:
        logger.info(f"{section} OPTION not existed!")
        return None, False
    res = (server, sponsor)
    logger.info(res)
    return res, True

def clearini_annc():
    delete_file(c.appdata_annc_ini)
    
def loadini_subscribe_kw2sound():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.subscribe_ini, encoding='utf-8')
    logger.info(c.subscribe_ini)
    
    if ok == False:
        return None, ok

    # 获取默认段落的所有键值对
    items = config.items(c.INI_SUBSCRIBE_SECTION)

    # 打印所有键值对
    for key, value in items:
        print(f"{key} = {value}")
    return items, True

def loadini_shotrect():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.shot_rect_ini, encoding='utf-8')
    logger.info(f"load short rect: {c.shot_rect_ini}")
    
    if ok == False:
        return None, None, ok

    rects_str = config.get(c.INI_SHOTRECT_SECTION, c.INI_SHOTRECT_OPTION_QA)
    logger.info(f"{c.INI_SHOTRECT_OPTION_QA}: {rects_str}")
    qa = eval(rects_str)
    
    rects_str = config.get(c.INI_SHOTRECT_SECTION, c.INI_SHOTRECT_OPTION_COORD)
    logger.info(f"{c.INI_SHOTRECT_OPTION_COORD}: {rects_str}")
    coord = eval(rects_str)
    
    return qa, coord, True

def dumpini_shotrect(rect_qa, rect_coord):
    try:
        logger.info(f"start dump short rect coord QA: {rect_qa} Coord: {rect_coord}")
        # 创建ConfigParser对象
        config = configparser.ConfigParser()

        # 添加一个新的section
        # 添加一个新的section
        section = c.INI_SHOTRECT_SECTION
        config.add_section(section)
        
        option = c.INI_SHOTRECT_OPTION_QA
        value = json.dumps(rect_qa)
        config.set(section, option, value)
        
        option = c.INI_SHOTRECT_OPTION_COORD
        value = json.dumps(rect_coord)
        config.set(section, option, value)

        # 写入到文件
        with open(c.shot_rect_ini, 'w') as configfile:
            config.write(configfile)
            logger.info(f"dump shot rect coord QA: {rect_qa} Coord: {rect_coord} ok")
    except FileNotFoundError:
        logger.error(f"File not found error. Unable to open file: {c.shot_rect_ini}")
    except PermissionError:
        logger.error(f"Permission error. Unable to write to file: {c.shot_rect_ini}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {str(e)}")
        
def loadini_price():
    # 创建ConfigParser对象
    config = configparser.ConfigParser()

    # 读取INI文件
    ok = config.read(c.price_ini, encoding='utf-8')
    logger.info(c.price_ini)
    
    if ok == False:
        return None, ok

    # 获取默认段落的所有键值对
    items = config.items(c.INI_PRICE_SECTION)

    res = {}
    # 打印所有键值对
    for key, value in items:
        print(f"{key} = {value}")
        res[key] = value
    return res, True

def dumpini_price(items):
    try:
        logger.info(f"start dump price {items}")
        # 创建ConfigParser对象
        config = configparser.ConfigParser()
        
        # 添加一个新的section
        section = c.INI_PRICE_SECTION
        config.add_section(section)
        for key, value in items.items():
            # print(f"dump {key} = {value} {type(key)}")
            
            option = key
            value = str(value)
            config.set(section, option, value)

        # 写入到文件
        with open(c.price_ini, 'w') as configfile:
            config.write(configfile)
            logger.info(f"dump price {items} finish")
    except FileNotFoundError:
        logger.error(f"File not found error. Unable to open file: {c.price_ini}")
    except PermissionError:
        logger.error(f"Permission error. Unable to write to file: {c.price_ini}")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {str(e)}")
    
if __name__ == '__main__':
    # dir_check()
    # dumpini_user("admin", "aa@123.com", "token_example", "123")
    # loadini_user()
    # clearini_user()
    
    # dumpini_setting("60.205.183.57", "9091", "0.0.0")
    # loadini_setting()
    # clearini_setting()
    
    # loadini_annc()
    # loadini_subscribe_kw2sound()
    # loadini_shotrect()
    # dumpini_shotrect(c.qa_shot_rect_default, c.coord_shot_rect_default)
    
    items, ok = loadini_price()
    # print(items)
    items['xlg'] = 799999
    dumpini_price(items)